<style lang="less">
  @import '../styles/common.less';
  @import '../tables/components/table.less';
</style>

<template>
  <div>
    <Row :gutter="10">
      <Card>
        <div class="table-head">
          <!--<Button type="primary" class="Button" @click="ExportData()">导出数据</Button>-->
          <Button type="primary" class="Button" @click="remove()">删除</Button>
          <Button type="primary" class="Button" @click="add()">添加</Button>
        </div>
        <Row class="margin-top-10">
          <Table stripe border :columns="columns" :data="data" @on-row-click="onRowData"
                 @on-selection-change="selectionChange"></Table>
        </Row>
        <div style="margin: 10px;overflow: hidden;height: 36px;">
          <div style="float: right;">
            <Page :total="total" :current="page" @on-change="changePage" show-elevator></Page>
          </div>
        </div>
      </Card>
      <!--详情-->
      <Modal v-model="showCurrentTableData" :width="600" :mask-closable="false" :closable="false"
             class-name="vertical-center-modal" class="Modal-Detail-div">
        <h3 slot="header" style="color:#2D8CF0">详情</h3>
        <Form label-position="top">
          <FormItem label="标题">
            <div class="dataDetail-div" v-text="dataDetail.title"></div>
          </FormItem>
          <FormItem label="创建人">
            <div class="dataDetail-div" v-text="dataDetail.uname"></div>
          </FormItem>
          <FormItem label="创建时间">
            <div class="dataDetail-div" v-text="dataDetail.create_time"></div>
          </FormItem>
          <FormItem label="状态">
            <div class="dataDetail-div" v-text="dataDetail.status"></div>
          </FormItem>
          <FormItem label="是否匿名">
            <div class="dataDetail-div" v-text="dataDetail.anonymous==true ? '是' : '否'"></div>
          </FormItem>
          <FormItem label="问题描述" v-if="dataDetail.content">
            <div class="dataDetail-div" v-text="dataDetail.content"></div>
          </FormItem>
          <FormItem label="任务负责人" v-if="dataDetail.task_chargeName && dataDetail.task_chargeName!=''">
            <div class="dataDetail-div" v-text="dataDetail.task_chargeName"></div>
          </FormItem>
          <FormItem label="任务状态" v-if="dataDetail.task_status && dataDetail.task_status!=''">
            <div class="dataDetail-div" v-text="dataDetail.task_status"></div>
          </FormItem>
          <FormItem label="图片" v-if="dataDetail.accessory && dataDetail.accessory.length > 0">
            <div class="dataDetail-div">
              <img v-for="el in dataDetail.accessory" :src="el.url" class="img">
            </div>
          </FormItem>
        </Form>
        <div slot="footer">
          <Button type="text" @click="hideDetailModal">取消</Button>
          <Button type="info" @click="toTask('dataDetail')" v-if="task_id == ''">转为任务</Button>
        </div>
      </Modal>
      <!--编辑-->
      <Modal v-model="addCurrentTableData" :width="600" :mask-closable="false" :closable="false"
             class-name="vertical-center-modal" class="Modal-Detail-div">
        <h3 slot="header" style="color:#2D8CF0">编辑</h3>
        <Form label-position="top">
          <FormItem label="标题">
            <Input v-model="addData.title" placeholder="标题"></Input>
          </FormItem>
          <FormItem label="问题描述">
            <Input v-model="addData.content" type="textarea" class="textarea_resize"
                   :autosize="{minRows: 3}" placeholder="内容"></Input>
          </FormItem>
          <FormItem label="是否匿名">
            <i-switch v-model="addData.anonymous" size="large">
              <span slot="open">是</span>
              <span slot="close">否</span>
            </i-switch>
          </FormItem>
          <FormItem label="图片">
            <div class="dataDetail-div chooseUser accessory">
              <img v-for="el in addData.accessory" :src="el.url" class="img">
              <Upload
                  :before-upload="handleUpload" action="" accept="image/*" :format="format"
                  :multiple="true">
                <Button icon="ios-cloud-upload-outline">选择文件</Button>
              </Upload>
            </div>
          </FormItem>
        </Form>
        <div slot="footer">
          <Button type="text" @click="hideAddModal">取消</Button>
          <Button type="info" @click="toTask('update')" v-if="ajaxType == 'update' && task_id == ''">转为任务</Button>
          <Button type="primary" :loading="saveLoading" @click="save()">确定</Button>
        </div>
      </Modal>
    </Row>
  </div>
</template>

<script>
  import Cookies from 'js-cookie';
  import Util from '../../libs/util';
  import Utils from '../../libs/mod.utils';
  import String from '../../libs/mod.string';
  import Modal from '../../libs/mod.Modal';
  export default {
    components: {},
    data () {
      return {
        total: 0,
        page: 1,
        size: 10,
        id: '',
        searchConName: '',
        searchConTel: '',
        showCurrentTableData: false,
        loading: true,
        showCurrentColumns: [],
        editInlineAndCellData: [],
        columns: [
          {
            type: 'selection',
            width: 60,
            align: 'center'
          },
          {
            key: 'title',
            title: '标题',
          },
          {
            key: 'uname',
            title: '创建人',
          },
          {
            key: 'anonymous',
            title: '是否匿名',
            width: 100,
            render: (h, params) => {
              return h('div', [
                h('span', params.row.anonymous == true ? '是' : '否')
              ]);
            }
          },
          {
            key: 'status',
            title: '状态',
            width: 100
          },
          {
            key: 'create_time',
            title: '创建时间',
            width: 200
          },
          {
            title: 'Action',
            key: 'action',
            width: 150,
            align: 'center',
            render: (h, params) => {
              return h('div', [
                h('Button', {
                  props: {
                    type: 'primary',
                    size: 'small'
                  },
                  style: {
                    marginRight: '5px'
                  },
                  on: {
                    click: e => {
                      e.stopPropagation();
                      var data = params.row;
                      this.update(data, params.index);
                    }
                  }
                }, '修改')
              ]);
            }
          }
        ],
        data: [],
        dataDetail: {},
        initTable: [],
        format: Util.constant.format,
        addCurrentTableData: false,
        saveLoading: false,
        ajaxType: 'add',
        addData: {
          title: '',
          content: '',
          anonymous: false,
          accessory: [],
        },
        selectionArr: [],
        task_id: '',
        comePageTime: 0,// 进入页面的时间戳
      };
    },
    beforeMount: function () {
      var _this = this;
      var comePageTime = _this.comePageTime;
      var timestamp = new Date().getTime();
      _this.comePageTime = timestamp;
    },
    beforeDestroy: function () {
      var _this = this;
      var comePageTime = _this.comePageTime;
      var timestamp = new Date().getTime();
      var type = Util.constant.statistical_type.city.id;
      var seconds = Math.ceil((parseInt(timestamp) - parseInt(comePageTime)) / 1000);
      Util.statistical(_this, type, seconds);//保存数据
    },
    mounted () {
      this.getData();
    },
    methods: {
      getData () {
        var _this = this;
        var data = {
          uid: Util.toJson(localStorage.getItem('userInfo')).id,
          page: _this.page,
          size: _this.size,
        };
        var params = {
          url: '/sd/city-management/list',
          type: Util.method.get,
          data: data,
          success: _successFun
        };
        Util.ajax(_this, params);
        function _successFun(res) {
          if (res.result == 0) {
            var _data = res.data || [];
            _this.total = res.rows;
            _this.data = _data;
          } else {
            _this.$Message.error('查询信息失败!');
          }
        }
      },
      handleSearch () {
        var _this = this;
        _this.page = 1;
        var searchConName = _this.searchConName;
      },
      changePage (page) {
        var _this = this;
        console.log('page', page);
        _this.page = page;
        _this.getData();
      },
      onRowData: function (data, index) {
        var _this = this;
        _this.show(index, data);
      },
      show: function (index, data) {
        var _this = this;
        var id = data.id;
        _this.id = id;

        var data = {
          id: _this.id,
        };
        var params = {
          url: '/sd/city-management/query',
          type: Util.method.get,
          data: data,
          success: _successFun
        };
        Util.ajax(_this, params);
        function _successFun(res) {
          if (res.result == 0) {
            var _data = res.data || [];
            var task = _data.task;
            _this.task_id = task.id ? task.id : '';
            var charge = task.charge || {};
            var task_chargeName = charge.name ? charge.name : '';
            var status = task.status || '';
            switch (status) {
              case "not-begun" :
                status = '未完成';
                break;
              case "started" :
                status = '已开始';
                break;
              case "delayed" :
                status = '已延期';
                break;
              case "finished" :
                status = '已完成';
                break;
              case "archived" :
                status = '已归档';
                break;
              case "ahead-finished" :
                status = '提前完成了';
                break;
              case "overtime-finished" :
                status = '延期完成了';
                break;
              default:
                break;
            }
            _data.task_chargeName = task_chargeName;
            _data.task_status = status;
            _this.dataDetail = _data;
            _this.showCurrentTableData = true;
          } else {
            _this.$Message.error('查询信息失败!');
          }
        }
      },
      // 隐藏详情页面
      hideDetailModal: function () {
        var _this = this;
        _this.showCurrentTableData = false;
      },
      asyncOK: function () {
        var _this = this;
        _this.showCurrentTableData = false;
      },
      // 选中文件
      handleUpload: function (file) {
        var _this = this;
        _this.UploadFile(file);
        return false;
      },
      // 上传文件
      UploadFile: function (file) {
        var _this = this;
        var name = file.name;
        var arr = name.split('.');
        var type = arr[arr.length - 1];
        if (!(Util.constant.format.indexOf(type) > -1)) {
          _this.$Message.error('请上传图片!');
          return false;
        }
        var formData = new FormData();
        formData.append("file", file);
        formData.append("type", "image");
        var params = {
          url: '/file/addFile',
          type: Util.method.post,
          data: formData,
          success: _successFun
        };
        Util.ajax(_this, params);
        function _successFun(res) {
          if (res.result == 0) {
            var data = res.data;
            var id = data.id;
            var name = data.name;
            var url = data.url;
            var obj = {
              id: id,
              name: name,
              url: url,
            };
            _this.addData.accessory.push(obj);
          } else {
            _this.$Message.error('上传失败!');
          }
        }
      },
      // 删除附件
      delAccessory: function (el) {
        var _this = this;
        var id = el.id;
        var accessory = _this.addData.accessory;
        for (var k in accessory) {
          if (!accessory[k]) {
            continue;
          }
          if (id == accessory[k].id) {
            var del = accessory.splice(k, 1);
            break;
          }
        }
        _this.addData.accessory = accessory;
      },
      // 列表多选 选中数据
      selectionChange: function (selection) {
        var _this = this;
        _this.selectionArr = selection;
      },
      // 隐藏编辑页面
      hideAddModal: function () {
        var _this = this;
        _this.addCurrentTableData = false;
      },
      // 显示添加界面
      add: function () {
        var _this = this;
        _this.addData.title = '';
        _this.addData.content = '';
        _this.addData.anonymous = false;
        _this.addData.accessory = [];
        _this.ajaxType = 'add';
        _this.addCurrentTableData = true;
      },
      // 保存数据
      save: function () {
        var _this = this;
        var title = _this.addData.title;
        var content = _this.addData.content;
        var anonymous = _this.addData.anonymous;
        var accessory = _this.addData.accessory;
        if (!(title && title != '')) {
          _this.$Message.error('请填写标题!');
          return false;
        }
        if (!(content && content != '')) {
          _this.$Message.error('请填写问题描述!');
          return false;
        }
        var images = [];
        for (var k in accessory) {
          if (!accessory[k]) {
            continue;
          }
          images.push(accessory[k].id);
        }
        var data = {
          id: _this.id,
          uid: Util.toJson(localStorage.getItem('userInfo')).id,
          openid: '',
          title: title,
          content: content,
          anonymous: anonymous,
          images: images,
        };
        var url = '/sd/city-management/add';
        if (_this.ajaxType == 'update') {
          url = '/sd/city-management/update';
        }
        var params = {
          url: url,
          type: Util.method.get,
          data: data,
          success: _successFun
        };
        Util.ajax(_this, params);
        _this.saveLoading = true;
        function _successFun(res) {
          _this.saveLoading = false;
          if (res.result == 0) {
            _this.page = 1;
            _this.getData();
            _this.addCurrentTableData = false;
            _this.addData.title = '';
            _this.addData.content = '';
            _this.addData.anonymous = false;
            _this.addData.accessory = [];
          } else {
            _this.$Message.error('保存信息失败!');
          }
        }
      },
      // 显示修改界面
      update: function (data, index) {
        var _this = this;
        _this.ajaxType = 'update';
        var id = data.id;
        _this.id = id;
        var data = {
          id: _this.id,
        };
        var params = {
          url: '/sd/city-management/query',
          type: Util.method.get,
          data: data,
          success: _successFun
        };
        Util.ajax(_this, params);
        function _successFun(res) {
          if (res.result == 0) {
            var _data = res.data || [];
            var task = _data.task;
            _this.task_id = task.id ? task.id : '';
            _this.addData.title = _data.title;
            _this.addData.content = _data.content;
            _this.addData.anonymous = _data.anonymous;
            _this.addData.accessory = _data.accessory;
            _this.addCurrentTableData = true;
          } else {
            _this.$Message.error('查询信息失败!');
          }
        }
      },
      // 删除
      remove: function () {
        var _this = this;
        var selectionArr = _this.selectionArr;
        if (selectionArr.length == 0) {
          _this.$Message.error('请填选择要删除的数据!');
          return false;
        }
        var selectionIds = [];
        for (var k in selectionArr) {
          if (!selectionArr[k]) {
            continue;
          }
          var id = selectionArr[k].id;
          selectionIds.push(id);
        }
        Modal.confirm(_this, {content: '确定删除选中的信息？'}, function () {
          var data = {
            id: selectionIds,
          };
          var params = {
            url: '/sd/city-management/deleteMultiple',
            type: Util.method.get,
            data: data,
            success: _successFun
          };
          Util.ajax(_this, params);
          function _successFun(res) {
            if (res.result == 0) {
              _this.page = 1;
              _this.getData();
            } else {
              _this.$Message.error('删除信息失败!');
            }
          }
        }, function () {
        });
      },
      // 导出
      ExportData: function () {
        var _this = this;
        var fields = [
          {
            field: 'id',
            title: '#',
            type: 'int',
            order: 1,
          },
          {
            field: 'name',
            title: '姓名',
            type: 'varchar',
            order: 2,
          },
          {
            field: 'anonymous',
            title: '是否匿名',
            type: 'varchar',
            order: 3,
          },
          {
            field: 'content',
            title: '内容',
            type: 'varchar',
            order: 4,
          },
          {
            field: 'create_time',
            title: '时间',
            type: 'datetime',
            order: 5,
          },
        ];
        var fieldsStr = Util.toStr(fields);
        var data = {
          uid: Util.toJson(localStorage.getItem('userInfo')).id,
          type: 'app-suggest',
          fields: fieldsStr,
        };
        var params = {
          url: '/file/db2excle',
          type: Util.method.post,
          data: data,
          success: _successFun
        };
        Util.ajax(_this, params);
        function _successFun(res) {
          if (res.result == 0) {
            var url = res.data;
            var date = Utils.dateToDateString(new Date());
            Utils.DownloadFile(url, '导出城市管理_' + date + '.xlsx');
          } else {
            _this.$Message.error('导出信息失败!');
          }
        }
      },
      // 转到任务
      toTask: function (from) {
        var _this = this;
        var city_id = _this.id;
        var title = '';
        var content = '';
        if (from == 'update') {
          title = _this.addData.title;
          content = _this.addData.content;
        } else if (from == 'dataDetail') {
          title = _this.dataDetail.title;
          content = _this.dataDetail.content;
        }
        var data = {
          city_id: city_id,
          title: title,
          content: content,
        };
        sessionStorage.setItem('city_data', Util.toStr(data));
        Util.openNewPage(_this, 'task_index');
        _this.$router.push({
          name: 'task_index'
        });

        _this.addCurrentTableData = false;
        _this.showCurrentTableData = false;
      },
    }
  };
</script>
